package com.yunhe.policyfulfillment.authority.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.model.mybatis.PageResult;
import com.yunhe.common.util.DateTimeUtils;
import com.yunhe.common.util.MD5Util;
import com.yunhe.policyfulfillment.authority.domain.PolicyOrg;
import com.yunhe.policyfulfillment.authority.domain.PolicyRole;
import com.yunhe.policyfulfillment.authority.domain.PolicyUser;
import com.yunhe.policyfulfillment.authority.model.DisableRecoveryUser;
import com.yunhe.policyfulfillment.authority.model.PolicyUserChangePassword;
import com.yunhe.policyfulfillment.authority.model.PolicyUserQueryCondition;
import com.yunhe.policyfulfillment.authority.model.UserLogin;
import com.yunhe.policyfulfillment.authority.repository.IPolicyUserRepository;
import com.yunhe.policyfulfillment.authority.service.IPolicyOrgService;
import com.yunhe.policyfulfillment.authority.service.IPolicyUserService;
import com.yunhe.policyfulfillment.authority.service.PolicyRoleService;
import com.yunhe.policyfulfillment.util.MyHeaderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yunhe.common.util.CollectionUtil;

import java.util.*;

/**
 * @ClassName PolicyUserServiceImpl
 * @Description TODO
 * @Author HeTao
 * @Date 2021/7/22 17:00
 * @Version 1.0
 **/
@Service
public class PolicyUserServiceImpl implements IPolicyUserService {

    private static final String SALT_M = "zcdx";
    private static final String SALT_V = "@zcdx";

    private static final String rootDefaultPassword = "ABcd1234";

    @Autowired
    private IPolicyUserRepository policyUserDAO;

    @Autowired
    private MyHeaderUtil myHeaderUtil;

    @Autowired
    private PolicyRoleService policyRoleService;

    @Autowired
    private IPolicyOrgService policyOrgService;


    @Override
    public void deletePolicyUser(List<Long> ids) {
        if(!CollectionUtil.isEmpty(ids)){
            for (long id : ids) {
                policyUserDAO.deletePolicyUserByPrimaryKey(id);
            }
        }

    }

    @Override
    public PolicyUser backPolicyUserlLogin(UserLogin userLogin) {
        userLogin.setPassword(MD5Util.encode(userLogin.getPassword(),SALT_M));
        return policyUserDAO.backPolicyUserlLogin(userLogin);
    }

    public static void main(String[] args) {
        System.out.println(MD5Util.encode("test",SALT_V));
    }

    @Override
    public List<PolicyUser> findPolicyUsers() {
        return policyUserDAO.findPolicyUsers();
    }

    @Override
    public List<PolicyUser> findPolicyUsersByOrgId(int currentAuditOrg) {
        return policyUserDAO.findPolicyUsersByOrgId(currentAuditOrg);
    }

    @Override
    public PolicyUser findPolicyUserById(long approvePerson) {
        PolicyUser policyUser = policyUserDAO.searchPolicyUserByPrimaryKey(approvePerson);
        if(policyUser != null){
            policyUser.setPassword(null);
            if(policyUser.getRoleId() != null){
                PolicyRole policyRole = policyRoleService.searchPolicyRoleByPrimaryKey(Long.valueOf(policyUser.getRoleId()));
                if(policyRole != null){
                    policyUser.setRoleTitle(policyRole.getTitle());
                }
            }
            if(policyUser.getOrgId() != null){
                PolicyOrg policyOrg = policyOrgService.searchPolicyOrgByPrimaryKey(policyUser.getOrgId());
                if(policyOrg != null){
                    policyUser.setOrgName(policyOrg.getOrgName());
                }
            }
            if(policyUser.getCreatePerson() != null){
                PolicyUser createPerson = policyUserDAO.searchPolicyUserByPrimaryKey(policyUser.getCreatePerson());
                if(createPerson != null){
                    policyUser.setCreatePersonName(createPerson.getUserName());
                }
            }
        }
        return policyUser;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createPolicyUser(PolicyUser policyUser) throws ArgumentErrorException {
        processBeforeSave(policyUser);
        policyUserDAO.createPolicyUserSelective(policyUser);
    }

    private void processBeforeSave(PolicyUser policyUser) throws ArgumentErrorException {
        PolicyUser headerUser = myHeaderUtil.getHeaderUser();
        if (headerUser == null) {
            throw new ArgumentErrorException("登录信息已失效,请重新登录!");
        }
        policyUser.setCreatePerson(headerUser.getId());
        //校验账号是否重复
        List<PolicyUser> policyUsers = policyUserDAO.findPolicyUserByUserAccount(policyUser.getUserAccount());
        if(!CollectionUtil.isEmpty(policyUsers)){
            throw new ArgumentErrorException("当前账号已经存在用户！");
        }
        policyUser.setPassword(MD5Util.encode(policyUser.getPassword(), SALT_M));
        //通过角色id 查询角色编码
        PolicyRole policyRole = policyRoleService.searchPolicyRoleByPrimaryKey(Long.valueOf(policyUser.getRoleId()));
        if(policyRole !=  null){
            policyUser.setRoleName(policyRole.getRoleCode());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePolicyUser(PolicyUser policyUser) throws ArgumentErrorException {
        PolicyUser headerUser = myHeaderUtil.getHeaderUser();
        if (headerUser == null) {
            throw new ArgumentErrorException("登录信息已失效,请重新登录!");
        }
        String remark = null;
        if("01".equals(policyUser.getActivity())){
            remark = headerUser.getUserName()+ DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date())+"恢复";
        }else {
            remark = headerUser.getUserName()+ DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date())+"禁用";
        }
        policyUser.setPassword(null);
        policyUser.setRemark(remark);
        policyUser.setUpdatePerson(headerUser.getId());
        //通过角色id 查询角色编码
        PolicyRole policyRole = policyRoleService.searchPolicyRoleByPrimaryKey(Long.valueOf(policyUser.getRoleId()));
        if(policyRole !=  null){
            policyUser.setRoleName(policyRole.getRoleCode());
        }
        policyUserDAO.updatePolicyUserByPrimaryKeySelective(policyUser);
    }

    @Override
    public PageResult findPolicyUserByCondition(PolicyUserQueryCondition policyUserQueryCondition) {
        PageResult result = null;
        PageHelper.startPage(policyUserQueryCondition.getPage(), policyUserQueryCondition.getSize());
        List<PolicyUser> policyUsers = policyUserDAO.findPolicyUserByCondition(policyUserQueryCondition);
        if(!CollectionUtil.isEmpty(policyUsers)){
            policyUsers.forEach(policyUser -> {
                policyUser.setPassword(null);
                if(policyUser.getRoleId() != null){
                    PolicyRole policyRole = policyRoleService.searchPolicyRoleByPrimaryKey(Long.valueOf(policyUser.getRoleId()));
                    if(policyRole != null){
                        policyUser.setRoleTitle(policyRole.getTitle());
                    }
                }
                if(policyUser.getOrgId() != null){
                    PolicyOrg policyOrg = policyOrgService.searchPolicyOrgByPrimaryKey(policyUser.getOrgId());
                    if(policyOrg != null){
                        policyUser.setOrgName(policyOrg.getOrgName());
                    }
                }
                if(policyUser.getCreatePerson() != null){
                    PolicyUser createPerson = policyUserDAO.searchPolicyUserByPrimaryKey(policyUser.getCreatePerson());
                    if(createPerson != null){
                        policyUser.setCreatePersonName(createPerson.getUserName());
                    }
                }
            });
            PageInfo<PolicyUser> pageInfo = new PageInfo<>(policyUsers);
            result = new PageResult(policyUserQueryCondition.getPage(), policyUserQueryCondition.getSize(),
                    (int) pageInfo.getTotal(), policyUsers);
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String resetPassword(List<Long> ids) throws ArgumentErrorException {
        if (CollectionUtil.isEmpty(ids)) {
            throw new ArgumentErrorException("请选择用户进行操作！");
        }
        PolicyUser headerUser = myHeaderUtil.getHeaderUser();
        if (headerUser == null) {
            throw new ArgumentErrorException("登录信息已失效,请重新登录!");
        }
        for (Long id : ids) {
            PolicyUser policyUser = policyUserDAO.searchPolicyUserByPrimaryKey(id);
            policyUserDAO.updatePassword(Long.valueOf(id), MD5Util.encode(MD5Util.encode(rootDefaultPassword, SALT_V), SALT_M),headerUser.getId());
//            //发短信
//            if (policyUser != null && policyUser.getPhone() != null) {
//                String phone = policyUser.getPhone();
//                String password = rootDefaultPassword;
//                Map<String, String> map = new HashMap<>();
//                map.put("code", password);
//                String templateCode = "SMS_218727647";
//                String templateParam = "{\"code\":\"" + password + "\"}";
//                try {
//                    SmsUtil.sendSms(phone, map, templateCode, templateParam);
//                } catch (Exception e) {
//                    throw new ArgumentErrorException("短信发送失败！");
//                }
//            }
        }
        return "将选择的用户的密码重置为系统默认密码，默认密码为："+rootDefaultPassword;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void disableRecoveryUser(DisableRecoveryUser disableRecoveryUser) throws ArgumentErrorException {
        PolicyUser headerUser = myHeaderUtil.getHeaderUser();
        if (headerUser == null) {
            throw new ArgumentErrorException("登录信息已失效,请重新登录!");
        }
        if(CollectionUtil.isEmpty(disableRecoveryUser.getIds())){
            throw new ArgumentErrorException("请选择用户进行操作！");
        }
        String remark = null;
        if("01".equals(disableRecoveryUser.getActivity())){
            remark = headerUser.getUserName()+ DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date())+"恢复";
        }else {
            remark = headerUser.getUserName()+ DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date())+"禁用";
        }
        List<Long> ids = disableRecoveryUser.getIds();
        String finalRemark = remark;
        ids.forEach(id->{
            policyUserDAO.updateActivity(id,disableRecoveryUser.getActivity(), finalRemark,headerUser.getId());
        });
    }

    @Override
    public void updatePassword(PolicyUserChangePassword policyUserChangePassword) throws ArgumentErrorException {
        PolicyUser policyUser = policyUserDAO.searchPolicyUserByPrimaryKey(policyUserChangePassword.getId());
        if(policyUser == null){
            throw new ArgumentErrorException("用户信息不存在！");
        }
        if(!policyUser.getPassword().equals(MD5Util.encode(policyUserChangePassword.getOldPassword(),SALT_M))){
            throw new ArgumentErrorException("旧密码验证错误");
        }
        policyUserDAO.updatePassword(policyUserChangePassword.getId(), MD5Util.encode(policyUserChangePassword.getNewPassword(),SALT_M), myHeaderUtil.getHeaderUserId());
    }

    @Override
    public List<PolicyUser> findPolicyUsersByRoleId(Long roleId) {
        return policyUserDAO.findPolicyUsersByRoleId(roleId);
    }

    @Override
    public void unbindRole(Long id) {
        policyUserDAO.unbindRole(id);
    }
}
